﻿using AutoMapper;
using Common.Infrastructrue.Interface;
using Common.Service;
using MediatR;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace RabitPart.ReadApi.Application.Loginfile
{
    public class LoginQueryCommanHandel : IRequestHandler<LoginQueryComman, ApiResult<LoginQueryCommanResponse>>
    {
        private readonly IUserResponstity userRE;
        private readonly ILogger<LoginQueryCommanHandel> logger;
        private readonly IMapper mapper;
        private readonly IConfiguration _configuration;

        public LoginQueryCommanHandel(IUserResponstity userRE, ILogger<LoginQueryCommanHandel> logger, IMapper mapper, IConfiguration _configuration)
        {
            this.userRE = userRE;
            this.logger = logger;
            this.mapper = mapper;
            this._configuration = _configuration;
        }

        public async Task<ApiResult<LoginQueryCommanResponse>> Handle(LoginQueryComman request, CancellationToken cancellationToken)
        {
            //用户名
            var list = await userRE.GetAsync(x => x.userName == request.userName);
            if (list == null)
            { 
                return await Task.FromResult(ApiResult<LoginQueryCommanResponse>.Fail("用户名不存在", StatusCodeEnum.Fail));
            }
            if (list.userpass != request.userpass)
            { 
                return await Task.FromResult(ApiResult<LoginQueryCommanResponse>.Fail("密码错误", StatusCodeEnum.Fail));
            }

            var alist = mapper.Map<LoginQueryCommanResponse>(list);
            alist.Token = GenerateJwtToken(request.userName  ,request.uId);
             
            return await Task.FromResult(ApiResult<LoginQueryCommanResponse>.Success(alist, StatusCodeEnum.Ok));

        }


        /// <summary>
        /// 生成jwt
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        private string GenerateJwtToken(string userName, int uId)
        {
            var claims = new[]
            {
                new Claim("Sub", userName),
               
                new Claim("Id", uId.ToString ())
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]));
            var creeds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                _configuration["Authentication:Issuer"],
                _configuration["Authentication:Audience"],
                claims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creeds
            );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }


    }
}
